<template>
	<view class="imageronghe">
		<view class="top">
			<button class="mubanBtnn" v-if="muban_url"  @click="onReset" >
				<uni-icons class="mubanBtnnClose" type="close"  size="50rpx" color="white"></uni-icons>
				</button>
			<view class="top_mid" v-if="muban_url">
				<video v-if="masterPage=='masterPage' && !pop_show" :src="muban_url" mode="aspectFill" class="imuban" autoplay="true" loop="true"
					show-fullscreen-btn="false"  enable-progress-gesture="false" show-mute-btn="true"
					play-btn-position="center" :poster="poster" id="myVideo" ></video>
					
					
				<view  class="top_fuceng"  v-if="ismoreface >0 && !pop_show">
					<image class="imuban active" mode="aspectFit" :src="ref_url"
						@click="onAddImgClick(2)"></image>
				</view>				
				<view v-if="!masterPage">
					<image src="/static/img/video.png" style="width: 60rpx;height: 50rpx;"></image>
						<text style="color: white;">视频</text>
					<!-- 	<uni-icons type="closeempty" size="30" color="#7E8BFF" class="top_fuceng2" @click="onReset"></uni-icons> -->
						<view class="triangle"></view>
						<uni-icons type="checkmarkempty" size="20" color="#7E8BFF" class="gougou" ></uni-icons>
				</view>
				<text  v-if="!masterPage" class="no_yulan_tip">由于相关规范，自定义内容不提供预览</text>
			</view>			
			
			
			<view class="top_mid" v-else @click="onUpVideoClick">
				<progress v-if="progress !=0 && progress !=100"   :percent="progress" show-info="true" stroke-width="10" class="progress" border-radius="10rpx"
							 />
				<image src="/static/img/pub_add.png" class="ii"></image>
				<text class="tt">请上传小于100M的模板视频(支持多人脸)</text>
				<text class="tt" style="text-decoration: underline;margin-top: 120rpx;" @click.stop="
							jumpto(
								'/src/pages/My/ShiPingJieShao/ShiPingJieShao?video_url=https://sm.2sxzw.com/media/admin_file/9/140_1724387860_iwsjd2K.mp4'
							)
						">点我查看视频教程</text> 
				<!--  -->
				<!-- 	<cover-view class="top_fuceng3" >
				</cover-view> -->
			</view>
		</view>
		
		<view class="middle">
			<view class="middle_1" :class="{ active: select_target_Index == index }" v-if="target_url"
				v-for="(item, index) in target_face_image_list" :key="index" @click="handleSelectAvater(index)">
				<image class="itarget" :src="target_face_image_list[index].face_image_url" mode="aspectFit"></image>
			</view>
			<view class="middle_1 middle_uoplaod_icon" @click="pop_show=true">
			<!-- 	<image src="/static/img/pub_add.png" class="ii"></image> -->
			</view>
			<text class="tt" v-if="!target_url">请提供正面拍摄且高清晰度的照片，面部需完整无遮挡。 照片轮廓越分明, 换脸融合效果越自然（非常重要）</text>
		</view>
		<view class="bottom">
			<view class="item">
				<view class="item_1" @click="onTongdaoTipClick">
					<text class="t1">换脸通道</text>
					<uni-icons type="info" class="t2" size="33rpx" color="red"></uni-icons>
				</view>
				<radio-group class="radioGroup" @change="changeTongdao" style="margin-right: 20rpx;">
					<label>
						<radio value="1" class="ro" /><text class="tt">通道1</text>
					</label>
					<label>
						<radio value="2" class="ro" /><text class="tt">通道2</text>
					</label>
					<label>
						<radio value="3" class="ro" /><text class="tt">通道3</text>
					</label>
					<label>
						<radio value="4" class="ro" /><text class="tt">通道4</text>
					</label>
				</radio-group>
			</view>
		</view>
		<button class="btn" @click="startBianLian" :loading="loadding" :disabled="loadding">开始换脸</button>
		<text v-if="price" class="t_price">{{ price }}</text>
		<view class="tip">
			<text class="t1">温馨提示</text>
			<text class="t2">
				1、进行人脸相关操作时，请选择正脸且清晰的人脸图片。
				2、通道一仅支持时长在30秒以内的视频，帧率不得高于30fps，分辨率为720p，不支持通过模板指定更换人脸。
				3、通道二视频时长不能超过60秒，帧率不高于30fps，分辨率不超过1080P，仅支持MP4、MOV格式，支持模板多人脸处理以及指定更换特定人脸。
				4、通道三最高支持时长为五分钟的视频，可处理1080p、30fps的视频文件，支持模板多人脸处理以及指定更换特定人脸。
				5、通道四最高支持时长为五分钟的视频，可处理4K、60fps的视频文件，支持模板多人脸处理以及指定更换特定人脸。
				6、在使用本服务过程中，您必须严格遵守国家相关法律法规以及本平台的服务协议。严禁将本服务用于任何非法目的，不得利用本服务从事违反法律法规、
				侵犯他人合法权益的行为。您需确保自身或应用用户使用、上传、发布的照片、素材等信息内容，已获得相关权利人的合法授权，不存在侵犯他人肖像权、版权等合法权益的问题，
				也不违反相关法律法规、政策规定以及公序良俗。您需自行对应用中用户使用本服务产生的内容负责，保证其合法合规。若违反上述要求引发任何纠纷，责任由您自行承担，本平台概不负责。
				同时，本平台有权立即终止您在本平台的所有服务，并保留追究您法律责任的权利。
			</text>
		</view>
		<imgPop :show="pop_show" @handleClose="pop_show=false" @getUploadImg="onAddImgClick(1)"></imgPop>

	</view>
</template>

<script>
	import imgPop from './cmp/imgPop.vue';
	import {
		videoronghe
	} from '@/src/api/huanlian.js';
	import {
		getUser,
		getAbilityPrice
	} from '@/src/utils/utils.js';
	import {
		upload_file
	} from '@/src/utils/uni-fetch.js';
	import {
		jumpto as jump
	} from '@/src/utils/utils.js';
	export default {
		components: {
			imgPop,
		},
		data() {
			return {
				ref_id: null,
				ref_url: null,
				ref_face_image_list: [],
				muban_id: null,
				target_id: null,
				muban_url: null,
				target_url: null,
				loadding: false,
				price: null,
				poster: null,
				target_face_image_list: [],
				select_target_Index: null, // 选中的avater
				tongdao: null,
				duration: null,
				pop_show: false,
				progress: 0,
				userData: null,
				isapp: false,
				masterPage:'',
				showMubanBtnnClose:true,
				ismoreface:false, // 视频是否为多人脸，用户上传的时候自己选择的，删除视频的时候要复原
			};
		},
		onLoad({
			muban_id,
			muban_url,
			poster,
			video_name,
			duration,
			masterPage 
		}) {
			this.userData = getApp().globalData.userData;
			this.muban_id = muban_id;
			this.muban_url = muban_url;
			this.poster = poster;
			this.duration = duration;
			this.masterPage=masterPage;
			this.currentMuban_url=muban_url;
			if (video_name) {
				uni.setNavigationBarTitle({
					title: video_name
				});
			}
			this.init_price();
			// #ifdef APP
			this.isapp = true
			// #endif
		},
		onShow() {
			// 页面显示时触发，继续播放视频
			const videoContext = uni.createVideoContext('myVideo', this);
			videoContext.play();
		},
		onHide() {
			// 页面隐藏时触发，暂停视频播放
			const videoContext = uni.createVideoContext('myVideo', this);
			videoContext.pause();
		},
		methods: {
			jumpto(url) {
				jump(url);
			},
			onTongdaoTipClick() {
				uni.showModal({
					title: '通道介绍',
					content: '每个通道来自不同公司的换脸算法，所以结果效果也各不相同，具体区别在页面下面有介绍，也可以自己体验不同效果',
					showCancel: false
				})
			},
			onReset() {
				this.ref_id = null
				this.ref_url = null
				this.ref_face_image_list = []
				this.muban_id = null
				this.muban_url = null
				this.duration = null
				this.poster = null
				this.masterPage='';
				this.ismoreface = false //视频是否为多人脸
			},
			changeTongdao(v) {
				this.tongdao = v.detail.value
				let defult = null
				if (!this.userData) {
					defult = '请先登陆'
				}
				if (!this.muban_id) {
					defult = '请先上传模板视频'
				}

				if (this.tongdao == 1) {
					this.price = this.get_price_default(this.price1, defult, 1)
					uni.showModal({
						title: '通道一',
						content: `支持30秒内视频\n${this.price}`,
						showCancel: false
					})
				} else if (this.tongdao == 2) {
					this.price = this.get_price_default(this.price2, defult, 2)
					uni.showModal({
						title: '通道二',
						content: `支持一分钟内视频\r\n${this.price}`,
						showCancel: false
					})
					if (this.target_face_image_list && this.target_face_image_list.length > 1) {
						this.target_id = null
						this.target_url = null
						this.select_target_Index = null;
						this.target_face_image_list = null
					}
				} else if (this.tongdao == 3) {
					this.price = this.get_price_default(this.price2, defult, 3)
					uni.showModal({
						title: '通道三',
						content: `支持五分钟内视频\r\n${this.price}`,
						showCancel: false
					})
				} else if (this.tongdao == 4) {
					this.price = this.get_price_default(this.price3, defult, 4)
					uni.showModal({
						title: '通道四',
						content: `支持五分钟内视频\r\n${this.price}`,
						showCancel: false
					})
				}

			},
			get_price_default(price, defult, tongdao) {
				const regex = /(\d+(\.\d+)?)(?=\s*积分)/g;
				const matches = price.match(regex);
				let userPoints = parseFloat(matches[0]);
				let memberPoints = parseFloat(matches[1]);
				if (tongdao != 1) {
					userPoints = (userPoints * this.duration).toFixed(2)
					memberPoints = (memberPoints * this.duration).toFixed(2)
				}
				let difference = (userPoints - memberPoints).toFixed(2);
				if (!defult) {
					if (this.userData.vip_time) {
						defult = `此视频需要${memberPoints}积分\n会员已为你节约${difference}积分`
					} else {
						defult = `此视频需要${userPoints}积分\n开通会员可获取专属折扣`
					}
				}
				return defult;
			},
			async onUpVideoClick() {
				let _this = this
				const [error, res] = await uni.chooseVideo({
					count: 1,
					compressed: false,
					sourceType: ['album']
				});
				if (error) {
					if (error.errCode == -2 || error.errCode == 0 || (error.errMsg && error.errMsg.includes('cancel'))) return;
					uni.showModal({
						title: '选取视频失败',
						content: error.errMsg,
						showCancel: false
					});
					return;
				}
				if (res.size > 100 * 1024 * 1024) {
					this.$showToast('您选择的视频太大了');
					return;
				}
				// console.log(res)
				// let encodedPath = encodeURIComponent(res.tempFilePath);
				// console.log(res.tempFilePath,encodedPath)
				try {
					let result = await upload_file({
						url: '/huanlian/huanlianupvideo/',
						file: {
							name: 'video',
							uri: res.tempFilePath
						},
						formData: {
							ability: 'VideoRongHe'
						}
					}, true, false, this.onUpload);
					uni.hideLoading()
					this.muban_id = result.data.i_id;
					this.muban_url = result.data.video_url;
					this.duration = result.data.duration;	
									
					
					
					uni.showModal({
						content: "您上传多视频中有多个人脸吗？",
						confirmText: '单人脸',
						cancelText: '多人脸',
						success: function(res) {
							if (res.cancel) {
								_this.ismoreface = true
								uni.showModal({
									content: '请上传一个视频里的人脸截图，以表明要替换的脸\n(正脸并且清晰的单人脸图片)',
									success: function(res) {
										if (res.confirm) {
											_this.onAddImgClick(2)
										}
									}
								});
							}
						}
					});
				} catch (e) {
					this.progress = 0
					uni.hideLoading()
					if (!e) return
					uni.showModal({
						title: '上传视频失败',
						content: e.errMsg,
						showCancel: false,
					});
					return
				}

			},
			handleSelectAvater(i) {
				// 处理选中头像
				this.select_target_Index = i;
			},

			async init_price() {
				try {
					this.price1 = await getAbilityPrice('VideoRongHe');
					this.price2 = await getAbilityPrice('VideoRongHe2');
					this.price3 = await getAbilityPrice('LongVideoPro');
					// this.price = this.price1
				} catch (e) {
					console.error(e, e.errMsg);
				}
			},
			async onAddImgClick(type) {
				const [error, res] = await uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'] //从相册选择
				});
				if (error) {
				if (error.errCode == -2 || error.errCode == 0 || (error.errMsg && error.errMsg.includes('cancel'))) return;
					uni.showModal({
						title: '选取图片失败',
						content: error.errMsg,
						showCancel: false
					});
					return;
				}
				try {

					let result = await upload_file({
						url: '/huanlian/up_image/',
						file: {
							name: 'image',
							uri: res.tempFilePaths[0]
						},
						formData: {
							img_type: 2,
							ability: 'VideoRongHe'
						}
					});
					if (!result.data.face_image_list || result.data.face_image_list.length == 0) {
						uni.showModal({
							showCancel: false,
							content: '您上传的图片中没有人脸，请重新上传'
						});
						this.target_id = null
						this.target_url = null
						this.select_target_Index = null;
						return;
					}
					if (type == 1) {
						if (result.data.face_image_list && result.data.face_image_list.length > 1 && this.tongdao ==
							2) {
							uni.showModal({
								content: '通道二人脸图只支持单人脸',
								showCancel: false
							});
							return;
						}
						this.target_id = result.data.id;
						this.target_url = res.tempFilePaths[0];
						this.target_face_image_list = result.data.face_image_list;
						if (this.target_face_image_list.length == 1) {
							this.select_target_Index = 0;
						} else {
							this.select_target_Index = null;
						}
					} else {// 上传视频指定人脸图
						if (result.data.face_image_list && result.data.face_image_list.length > 1) {
							uni.showModal({
								content: `此图只支持单个人脸,\n 但此图有${result.data.face_image_list.length}个人脸,\n请重新上传`,
								showCancel: false
							});
							this.muban_id = null //上传到人脸图不符合条件，就重新上传视频和指定图
							this.muban_url = null //上传到人脸图不符合条件，就重新上传视频和指定图
							this.ref_id = null //上传到人脸图不符合条件，就重新上传视频和指定图
							this.ref_url = null //上传到人脸图不符合条件，就重新上传视频和指定图
							return;
						}
						this.ref_id = result.data.id;
						this.ref_url = result.data.face_image_list[0].face_image_url;
					}

				} catch (e) {
					uni.hideLoading()
					if (!e) return
					//TODO handle the exception
					console.error(e.errMsg);
					uni.showModal({
						title: '上传图片失败',
						content: e.errMsg,
						showCancel: false,
					});
				}
			},
			async startBianLian() {
				let _this = this;
				if (!this.muban_id) {
					_this.$showToast('请上传模板视频');
					return;
				}
				if (this.select_target_Index == null) {
					_this.$showToast('请上传人脸图，并且选择人脸');
					return;
				}
				if (!this.tongdao) {
					_this.$showToast('请选择换脸通道');
					return;
				}
				if (this.ismoreface && !this.ref_id){
					uni.showModal({
						content:"您当前视频是多人脸，请上传视频中的截图，让系统知道您想换哪个人脸",
						success: function(res) {
							if (res.confirm) {
								_this.onAddImgClick(2)
							}
						}
					})
					
					return
				}
				try {
					this.loadding = true
					let result = await videoronghe({
						ref_id: this.ref_id ? this.ref_id : '', //如果视频有多个人脸，指定特定人脸ID
						tongdao: this.tongdao,
						template_id: this.muban_id,
						target_id: this.target_id,
						select_target_face_info: JSON.stringify(this.target_face_image_list[this
							.select_target_Index].face_rect)
					});
					uni.hideLoading();
					this.target_id = null
					this.target_url = null
					this.select_target_Index = null;
					this.target_face_image_list = null
					uni.navigateTo({
						url: '/src/pages/My/JobList/JobList'
					});
				} catch (e) {
					if (!e) return
					console.error(e, e.errMsg || e.message)
					uni.showModal({
						content: e.errMsg,
						showCancel: false
					});
				} finally {
					this.loadding = false
				}
			},
			onUpload(uploadTask) {
				let _this = this
				uploadTask.onProgressUpdate((res) => {
					_this.progress = res.progress
					// console.log('上传进度' + res.progress);
					// console.log('已经上传的数据长度' + res.totalBytesSent);
					// console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
				});
			},
			cleanTempFile(path) {
					uni.getFileSystemManager().unlink({
						filePath: path,
						success() {
							console.log('清理视频缓存成功')
						},
						fail(err) {
							console.error('清理失败（可能已自动释放）:', err);
						}
					});
				},
				isPureNumber(str) {
					return /^\d+$/.test(str); // 判断是否纯数字
				}

		}
	};
</script>

<style lang="scss">
	@import 'VideoRongHe.scss';
</style>